package com.jingdianjichi.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.subject.domain.convert.SubjectCategoryConverter;
import com.jingdianjichi.subject.domain.convert.SubjectLabelConverter;
import com.jingdianjichi.subject.domain.entity.SubjectCategoryBO;
import com.jingdianjichi.subject.domain.entity.SubjectLabelBO;
import com.jingdianjichi.subject.domain.service.SubjectCategoryDomainService;
import com.jingdianjichi.subject.domain.util.CacheUtil;
import com.jingdianjichi.subject.infra.basic.entity.SubjectCategory;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectCategoryService;
import com.jingdianjichi.subject.infra.basic.service.SubjectLabelService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Autowired
    private SubjectCategoryService subjectCategoryService;

    @Autowired
    private SubjectMappingService subjectMappingService;

    @Autowired
    private SubjectLabelService subjectLabelService;

    // labelThreadPool 是Bean对象的名字，创建时就指定了的
    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {

        // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
        if(log.isInfoEnabled()){
            log.info("log-info:{}", JSON.toJSONString(subjectCategoryBO));
        }

        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBO> queryPrimaryCategory() {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setCategoryType(1);
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryPrimaryCategory(subjectCategory);

        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConverter.INSTANCE
                .convertCategoryListToBoList(subjectCategoryList);
        return subjectCategoryBOList;
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);

        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);

        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConverter.INSTANCE
                .convertCategoryListToBoList(subjectCategoryList);
        // 补充每个类别下的题目数量
        subjectCategoryBOList.forEach(subjectCategoryBO1 -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(subjectCategoryBO1.getId());
            subjectCategoryBO1.setCount(subjectCount);
        });

        return subjectCategoryBOList;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    /**
     * @Description: 走的逻辑删除，update删除字段，而不是真实删除
     * @return:
     * @Author:  sky
     * @date:  2024/11/7 20:37
     */
    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count>0;
    }

    @Override
    @SneakyThrows
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List<SubjectCategoryBO> subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        // 查询大类下的所有小分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("log-info:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConverter.INSTANCE.convertCategoryListToBoList(subjectCategoryList);
        // 根据小分类id，获取对应包含的标签信息
        // 多线程优化，查询效率
        // 采用jdk1.8之后提供的CompletableFuture实现方式
        // 创建时，就可以直接指定任务的执行方法，以及提交的线程池
        // CompletableFuture.supplyAsync 是一个工厂方法，
        //  用于创建一个 CompletableFuture，该 CompletableFuture 会在指定的线程池中异步执行给定的 Supplier 函数。
        // () -> getLabelBOList(subjectCategoryBO1) 是一个 Supplier 函数，它返回一个 Map<Long, List<SubjectLabelBO>>
        // labelThreadPool 是一个 Executor，用于指定 CompletableFuture 应该在哪个线程池中执行。
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOList.stream().map(subjectCategoryBO1 ->
                        CompletableFuture.supplyAsync(() -> getLabelBOList(subjectCategoryBO1), labelThreadPool))
                .collect(Collectors.toList());
        // 取出CompletableFuture任务的执行结果，放到统一的map里面
        // get方法会阻塞，等待任务执行完成
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBO>> resutlMap = future.get();
                if(CollectionUtils.isEmpty(resutlMap)){
                    return;
                }
                map.putAll(resutlMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        subjectCategoryBOList.forEach(subjectCategoryBO1 -> {
            subjectCategoryBO1.setLabelBOList(map.get(subjectCategoryBO1.getId()));
        });

        return subjectCategoryBOList;
    }

    // 老式的FutureTask实现方式，不好实现回调方法
    /*
    // 任务队列
    List<FutureTask<Map<Long,List<SubjectLabelBO>>>> futureTaskList =  new LinkedList<>();
    // 存储任务处理完之后的map集合
    Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
    // 创建任务，任务里面指定执行方法，并交给任务队列管理
    // 线程池提交任务，去执行
    subjectCategoryBOList.forEach(subjectCategoryBO1 -> {
        FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask = new FutureTask<>(()->
                getLabelBOList(subjectCategoryBO1));
        futureTaskList.add(futureTask);
        labelThreadPool.submit(futureTask);
    });
    // 通过任务队列，获取futureTask任务返回的结果，get方法会阻塞等待
    for(FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask : futureTaskList){
        Map<Long, List<SubjectLabelBO>> resultMap = futureTask.get();
        if(CollectionUtils.isEmpty(resultMap)){
            continue;
        }
        map.putAll(resultMap);
    }
    // 通过小分类id，获取对应的标签List
    subjectCategoryBOList.forEach(subjectCategoryBO1 -> {
        subjectCategoryBO1.setLabelBOList(map.get(subjectCategoryBO1.getId()));
    });
    */


    private Map<Long,List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO subjectCategoryBO1){
//        if(log.isInfoEnabled()){
//            log.info("log-info:{}", JSON.toJSONString(subjectCategoryBO1));
//        }

        // key--value：小分类id--对应包含的所有标签的list
        Map<Long,List<SubjectLabelBO>> labelMap = new HashMap<>();

        // label表里面的category_id是记录所属大分类id
        // mapping表里面的category_id是记录所属小分类的id
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(subjectCategoryBO1.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        if(CollectionUtils.isEmpty(subjectMappingList)){
            return null;
        }
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> subjectLabelBOList = SubjectLabelConverter.INSTANCE.convertLabelListToBoList(subjectLabelList);

        labelMap.put(subjectCategoryBO1.getId(),subjectLabelBOList);

        return labelMap;
    }

}
